<script lang="ts" setup>
import { reactive, ref } from 'vue';

import { VbenForm, VbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { exportBOM } from '#/api/bom/bom';
import { exportFormSchema } from '#/views/bom/data';

// 定义props
interface Props {
  visible: boolean;
  bomIds?: string[]; // 可选，用于导出指定BOM
}

// 定义emits
interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 状态
const loading = ref(false);
const formRef = ref();
const formData = reactive({
  bom_ids: props.bomIds || [],
  export_format: 'excel',
  include_components: true,
  include_versions: false,
  include_substitutes: false,
  include_documents: false,
});

// 取消
const handleCancel = () => {
  emit('update:visible', false);
};

// 确认导出
const handleConfirm = async () => {
  try {
    loading.value = true;

    // 如果没有指定BOM ID，则导出所有BOM
    const exportParams = {
      bom_ids: formData.bom_ids.length > 0 ? formData.bom_ids : undefined,
      export_format: formData.export_format,
      include_components: formData.include_components,
      include_versions: formData.include_versions,
      include_substitutes: formData.include_substitutes,
      include_documents: formData.include_documents,
    };

    const { data } = await exportBOM(exportParams);

    // 处理文件下载
    const blob = new Blob([data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `bom_export_${new Date().toISOString().slice(0, 10)}.${formData.export_format}`;
    link.click();
    window.URL.revokeObjectURL(url);

    message.success('导出成功');
    emit('success');
    emit('update:visible', false);
  } catch (error) {
    message.error('导出失败');
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <VbenModal
    v-model:visible="visible"
    title="BOM导出"
    :width="600"
    :loading="loading"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <VbenForm ref="formRef" :schema="exportFormSchema" :model="formData" />
  </VbenModal>
</template>
